package com.h2cloud.reflection.test;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.h2cloud.reflection.test
 * @ClassName: reflectUtil
 * @Author: h2cloud
 * @CreateTime: 2022/11/20 9:09 下午
 * @Description:
 */
public class reflectUtil {

	public static final HashMap<Class, Map<String, Field>> cacheMap = new HashMap<>();

	public reflectUtil() {
		setClassFields(Person.class);
	}

	public static void setClassFieldsList(List<Class> cList) {
		for (Class c : cList) {
			setClassFields(c);
		}
	}

	// 设置类的属性执行器
	public static void setClassFields(Class c) {
		Map<String, Field> fieldMap = null;
		if (!cacheMap.containsKey(c)) {
			fieldMap = new HashMap<>();
			Field[] fields = c.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				fields[i].setAccessible(true);
				fieldMap.put(fields[i].getName(), fields[i]);
			}
			cacheMap.put(c, fieldMap);
		}
	}

	// 获取类中某个属性的执行器
	public static Field getField(Class c, String fieldName) {
		if (!cacheMap.containsKey(c)) {
			setClassFields(c);
		}
		return cacheMap.get(c).get(fieldName);
	}

	public static Object getFieldValue(Class c, Object originObj, String fieldName) {
		Object fieldValue = null;
		try {
			fieldValue = getField(c, fieldName).get(originObj);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return fieldValue;
	}
}
